package com.zoe.onelink.core.util.interceptor;

import com.zoe.onelink.common.exception.http.HttpClientException;
import com.zoe.onelink.core.property.http.HttpClientConfig;
import com.zoe.onelink.core.util.http.HttpClientInterceptor;
import com.zoe.onelink.core.util.http.model.HttpClientEntity;
import com.zoe.onelink.core.util.http.model.HttpClientResponse;
import lombok.RequiredArgsConstructor;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-06-30
 */
@RequiredArgsConstructor
public class HttpClientRateLimitInterceptor implements HttpClientInterceptor {

    private final AtomicInteger rateLimit = new AtomicInteger(0);
    private final HttpClientConfig clientProp;

    @Override
    public void beforeRequest(boolean async, HttpClientEntity entity) {
        if (!async && this.rateLimit.incrementAndGet() > this.clientProp.getMaxRequest()) {
            this.rateLimit.decrementAndGet();
            throw new HttpClientException("HttpClient rate limit :" + this.clientProp.getMaxRequest());
        }
    }

    @Override
    public <R> void afterRequest(boolean async, HttpClientEntity entity, HttpClientResponse<R> response) {
        if (!async) {
            this.rateLimit.decrementAndGet();
        }
    }

}
